package org.example;

/**
 * 搜索二维矩阵
 */
public class Solution21 {

    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }

        int m = matrix.length;
        int n = matrix[0].length;

        // 从右上角开始
        int row = 0;
        int col = n - 1;

        while (row < m && col >= 0) {
            if (matrix[row][col] == target) {
                return true;
            } else if (matrix[row][col] > target){
                col--; // 向左移动一列
            } else {
                row++; // 向下移动一行
            }
        }

        return false;
    }

}
